package cn.edu.scau.cmi.zhuangjunsheng.comprehension.DAO;

import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

import cn.edu.scau.cmi.zhuangjunsheng.comprehension.domain.Teacher;
import cn.edu.scau.cmi.zhuangjunsheng.comprehension.util.MySessionFactory;



public class TeacherDAO {
	public static final String NAME = "name";
	private Session session = MySessionFactory.getSession();
	
	public void save(Teacher tea) {
		try {
			Transaction transaction = session.beginTransaction();
			session.save(tea);
			transaction.commit();
		} catch (Exception e) {
			throw e;
		}
	}
	public void delete(Teacher tea) {
		try {
			Transaction transaction = session.beginTransaction();
			session.delete(tea);
			transaction.commit();
		}catch (Exception e) {
			throw e;
		}
	}
	public Teacher getById(long id) {
		try {
			Teacher inTeacher = (Teacher) session.get("cn.edu.scau.cmi.caocheng.hibernate.domain.Teacher", id);
			return inTeacher;
		} catch (Exception e) {
			throw e;
		}
	}
	public List findByExp(Teacher ins) {
		try {
			List rs = session.createCriteria("cn.edu.scau.cmi.caocheng.hibernate.domain.Teacher")
					.add(Example.create(ins)).list();
			return rs;
		} catch (Exception e) {

			throw e;
		}
	}
	public List findByPro(String name, Object val) {
		try {
			String query = "from Teacher as model where model." + name + "=?";
			Query query2 = session.createQuery(query);
			query2.setParameter(0, val);
			return query2.list();
		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
			throw e;
		}
	}
	public List findByName(String name) {
		return findByPro(NAME, name);
	}
	public List findAll() {
		try {
			String queryString = "from Teacher";
			Query queryObject = session.createQuery(queryString);
			return queryObject.list();
		} catch (Exception re) {
//			re.printStackTrace();
//			return null;
			throw re;
		}
	}
	public Teacher merge(Teacher detachedInstance) {
		try {
			Teacher result = (Teacher) session.merge(detachedInstance);
			return result;
		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
			throw e;
		}
	}

	public void attachDirty(Teacher instance) {
		try {
			session.saveOrUpdate(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void update(Teacher instance) {
		try {
			Transaction transaction = session.beginTransaction();
			session.update(instance);
			transaction.commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public void attachClean(Teacher instance) {
		try {
			session.buildLockRequest(LockOptions.NONE).lock(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
